package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.SysLog;
import com.itheima.factory.MapperFactory;
import com.itheima.mapper.SysLogMapper;
import com.itheima.service.SysLogService;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class SysLogServiceImpl implements SysLogService {
    //新增方法
    public void save(SysLog sysLog) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
        //调用持久层的方法
        mapper.save(sysLog);
        //关流释放资源
        sqlSession.commit();
        sqlSession.close();

    }

    //查询所有
    public List<SysLog> findAll(String pageNum, String pageSize, String stime) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
        int pageN = 1;
        int pageS = 4;
        //非空判断
        if (StringUtils.isNoneBlank(pageNum)) {
            pageN = Integer.parseInt(pageNum);
        }
        if (StringUtils.isNoneBlank(pageSize)) {
            pageS = Integer.parseInt(pageSize);
        }
        //设置分页参数
        PageHelper.startPage(pageN, pageS);

        if (StringUtils.isNoneBlank(stime)) {
            stime = stime.replace(" ", "");
        }
        //调用持久层的接口方法
        List<SysLog> list = mapper.findAll(stime);
        //对查询出来的日期进行处理
        for (SysLog log : list) {
            String visitTimeStr = log.getVisitTimeStr();
            String dateStr = exchange(visitTimeStr);
            log.setVisitTimeStr(dateStr);
        }
        //关流释放资源
        sqlSession.commit();
        sqlSession.close();
        return list;
    }

    //批量删除
    public boolean deleteByIds(String ids) {
        SqlSession sqlSession = null;
        boolean flag = false;//删除失败
        try {
            sqlSession = MapperFactory.getSqlSession();
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
            String[] id = ids.split(",");//["1","2","3"]
            mapper.deleteByIds(id);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //3、关闭资源
            sqlSession.commit();
            sqlSession.close();
        }

        return flag;

    }

    //生成报表
    public ByteArrayOutputStream getReport(String pageNum, String pageSize, String stime) throws IOException {
        SqlSession sqlSession = null;
        List<SysLog> list=null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
            //获取要展示的数据
            int pageN = 1;
            int pageS = 4;
            //非空判断
            if (StringUtils.isNoneBlank(pageNum)) {
                pageN = Integer.parseInt(pageNum);
            }
            if (StringUtils.isNoneBlank(pageSize)) {
                pageS = Integer.parseInt(pageSize);
            }
            //设置分页参数
            PageHelper.startPage(pageN, pageS);

            if (StringUtils.isNoneBlank(stime)) {
                stime = stime.replace(" ", "");
            }
            //调用持久层的接口方法
             list = mapper.findAll(stime);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //3、关闭资源
            sqlSession.commit();
            sqlSession.close();
        }
        //1.获取到对应的Excel文件，工作簿文件
        Workbook wb = new XSSFWorkbook();
        //2.创建工作表
        Sheet s = wb.createSheet("日志导出文件");
        //设置通用配置
//        s.setColumnWidth(4,100);
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);
        //制作标题
        //合并单元格
        s.addMergedRegion(new CellRangeAddress(1,1,1,7));
        Row row_1 = s.createRow(1);
        Cell cell_1_1 = row_1.createCell(1);
        cell_1_1.setCellValue("日志导出数据");
        //创建一个单元格样式
        CellStyle cs_title = wb.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
        cell_1_1.setCellStyle(cs_title);


        //制作表头
        String[] fields = {"ID","访问时间","访问用户","访问IP","资源URI",
                "执行时间","访问方法"};
        Row row_2 = s.createRow(2);
        s.setColumnWidth(1,10000);
        s.setColumnWidth(2,5000);
        for (int i = 0; i < fields.length; i++) {
            Cell cell_2_temp = row_2.createCell(1 + i); //++
            cell_2_temp.setCellValue(fields[i]);    //++
            cell_2_temp.setCellStyle(cs_field);
        }
        //制作数据区
        int row_index = 0;
        for (SysLog syslog : list) {
            int cell_index = 0;
            Row row_temp = s.createRow(3 + row_index++);

            Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
            cell_data_1.setCellValue(syslog.getId());    //++
            cell_data_1.setCellStyle(cs_field);

            Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
            cell_data_2.setCellValue(syslog.getVisitTimeStr());    //++
            cell_data_2.setCellStyle(cs_field);

            Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
            cell_data_3.setCellValue(syslog.getUsername());    //++
            cell_data_3.setCellStyle(cs_field);

            Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
            cell_data_4.setCellValue(syslog.getIp());    //++
            cell_data_4.setCellStyle(cs_field);

            Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
            cell_data_5.setCellValue(syslog.getUrl());    //++
            cell_data_5.setCellStyle(cs_field);

            Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
            cell_data_6.setCellValue(syslog.getExecutionTime());    //++
            cell_data_6.setCellStyle(cs_field);

            Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
            cell_data_7.setCellValue(syslog.getMethod());    //++
            cell_data_7.setCellStyle(cs_field);
        }
        //将内存中的workbook数据写入到流中
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        wb.close();
        return os;
    
    }



    //封装的去除数据库中的时分秒位的方法
    private String exchange(String dateStr) throws ParseException {
        //把字符串转换为日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateStr);
        //把日期格式转化为字符串返回
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
       return dateFormat.format(date);
    }
}
